#!/usr/bin/env python3
"""
快速启动脚本
自动初始化系统并启动服务
"""

import sys
import os
import subprocess
import time

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def check_dependencies():
    """检查依赖包"""
    print("📦 检查依赖包...")
    
    required_packages = [
        'fastapi',
        'uvicorn',
        'akshare',
        'pandas',
        'sqlalchemy',
        'plotly',
        'redis',
        'bcrypt',
        'python-jose'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
            print(f"✅ {package}")
        except ImportError:
            missing_packages.append(package)
            print(f"❌ {package} (缺失)")
    
    if missing_packages:
        print(f"\n⚠️ 发现缺失的依赖包: {', '.join(missing_packages)}")
        print("正在安装缺失的依赖包...")
        
        try:
            subprocess.check_call([
                sys.executable, "-m", "pip", "install"
            ] + missing_packages)
            print("✅ 依赖包安装完成")
        except subprocess.CalledProcessError:
            print("❌ 依赖包安装失败，请手动运行: pip install -r requirements.txt")
            return False
    
    return True

def run_initialization():
    """运行系统初始化"""
    print("\n🔧 运行系统初始化...")
    
    try:
        # 导入初始化模块
        from init_system import main as init_main
        
        success = init_main()
        if not success:
            print("❌ 系统初始化失败")
            return False
        
        print("✅ 系统初始化完成")
        return True
        
    except Exception as e:
        print(f"❌ 初始化过程中发生错误: {e}")
        return False

def start_server():
    """启动服务器"""
    print("\n🚀 启动服务器...")
    print("请稍等，服务器正在启动...")
    print("\n" + "="*60)
    
    try:
        import uvicorn
        
        print("🌐 服务器访问地址:")
        print("   🏠 集成仪表板: http://localhost:8000/dashboard")
        print("   📊 财务分析: http://localhost:8000")
        print("   📈 大盘数据: http://localhost:8000/market")
        print("   👥 用户管理: http://localhost:8000/auth")
        print("   📚 API文档: http://localhost:8000/docs")
        print("\n👤 默认管理员账号: admin / admin123")
        print("="*60)
        print("\n按 Ctrl+C 停止服务器")
        print()
        
        # 启动服务器
        uvicorn.run(
            "backend.app.main:app",
            host="0.0.0.0",
            port=8000,
            reload=True,
            log_level="info"
        )
        
    except KeyboardInterrupt:
        print("\n\n⏹️ 服务器已停止")
    except Exception as e:
        print(f"\n❌ 服务器启动失败: {e}")
        return False
    
    return True

def main():
    """主函数"""
    print("🚀 股票分析平台 - 快速启动")
    print("="*50)
    print("这个脚本将自动:")
    print("  1. 检查并安装依赖包")
    print("  2. 初始化数据库和管理员账号")
    print("  3. 启动Web服务器")
    print("="*50)
    
    # 询问用户是否继续
    try:
        response = input("\n是否继续? (y/n): ").lower().strip()
        if response not in ['y', 'yes', '是', '']:
            print("❌ 用户取消启动")
            return
    except KeyboardInterrupt:
        print("\n❌ 用户中断启动")
        return
    
    # 1. 检查依赖
    if not check_dependencies():
        print("\n❌ 依赖检查失败，请手动安装依赖后重试")
        return
    
    # 2. 运行初始化
    if not run_initialization():
        print("\n❌ 系统初始化失败")
        return
    
    # 3. 启动服务器
    print("\n⏳ 3秒后启动服务器...")
    time.sleep(3)
    
    start_server()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n⚠️ 用户中断程序")
    except Exception as e:
        print(f"\n❌ 程序运行出错: {e}")
        import traceback
        traceback.print_exc()
